<?php
/*
 * 运营后台团购活动操作入口
 */
class Controller_Admin_Tuan extends Controller_Template
{
	protected $_tuan = NULL;

	public function __construct($request,$response)
	{
		parent::__construct($request,$response);
		$this->template = 'smarty:admin/tuan/index';
		$this->_tuan    = new Tuan(); 
	}

	public function action_index()
	{
		$this->action_list();
	}

	/**
	 * 团购活动列表，在此可拖动各商品达到排序的目的，页面中可删除，在保存时增加，页面中可随时修改title;
	 */
	public function action_list($flag=false)
	{
		$goods_list = array();
		$max_count  = Kohana::config('tuan.max_tuan_goods');
		$startdate  = date('Y-m-d');
		$enddate    = date('Y-m-d', strtotime("+1 week", strtotime($startdate)-1));

		$goods_ids  = $this->request->query('goods_ids');

		$ids        = empty($goods_ids) ? array() : explode(',', $goods_ids);
		$tuan_list  = $this->_tuan->today_goods();
		
		if(!empty($ids))
		{
			foreach($ids as $k=>$id)
			{
				if(isset($tuan_list[$id]))
					unset($ids[$k]);
			}

			if(!empty($ids))
			{
				$query      = array('id'=>$ids);
				$goodsres   = Goods::search($query);
				$goods_list = $goodsres['list'];
				if(!empty($goods_list))
				{
					foreach($goods_list as & $g)
					{
						$img = Goods_Album::images($g['goods_id'],'large');
						$g['large_cover_thumb'] = $img[0]['img_url'];
					}
					$tuan_list  = array_merge($tuan_list, $goods_list);
				}
			}
		}

		$this->template->set('max_count',$max_count);
		$this->template->set('goods_ids',$goods_ids);
		$this->template->set('goods_list',$tuan_list);
		$this->template->set('startdate',$startdate);
		$this->template->set('enddate',$enddate);
		$this->template->set('flag',$flag);
		$this->template->set('function_name','tuan');
		$this->template->set('page_title','团购商品管理');
	}

	/**
	 * 设置某天整体团列表 批量保存；
	 *
	 * @param $day 提交某天数据；
	 * @post 接收商品数组；
	 */
	public function action_set_tuan_list()
	{
		$list = array();
		$post = $this->request->post();
		$flag = false;
		$sort = 1;
		foreach($post as $key => $t)
		{
			$tmp                = array();
			$exp                = explode('_',$key);
			$goods_id           = (int) $exp[1];
			if(!$goods_id)
				continue;
			if(isset($list[$goods_id]))
				continue;
			$tmp['goods_id']    = $goods_id;
			$tmp['sort']        = $sort;
			$tmp['title']       = $t;
			$tmp['start_time']  = strtotime(Arr::get($post, 'startdate_'.$goods_id, date('Y-m-d',strtotime(date('Y-m-d')))));
			$tmp['end_time']    = strtotime(Arr::get($post, 'enddate_'.$goods_id, date('Y-m-d',strtotime("+1 week",$tmp['start_time']-1)))) + (86400-1);
			$tmp['image']       = Arr::get($post, 'image_'.$goods_id, '');
			$list[$goods_id]    = $tmp;
			$sort++;
		}

		if($this->_tuan->set_goods($list))
			$flag = true;

		header("Location:/tuan/list/$flag");
		exit;
	}
}
